package com.wq.user.service;

import com.wq.common.util.IdWorker;
import com.wq.user.dao.UserDao;
import com.wq.user.entity.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;

    public User findById(String id){
        return userDao.selectById(id);
    }

    public List<User> findAll(){
        return userDao.selectList(null);
    }
    //发送验证码： 6位数
    public void sendSms(String phone){
        int min =100000;
        int max=999999;
        Random random=new Random();
        int code= random.nextInt(max);
        code=code<min?code+min:code;
        System.out.println(phone+"验证码为:"+code);
        //将验证码存储到redis中  并设置有效期为5分钟
        redisTemplate.boundValueOps("sms_code_phone"+phone)
                .set("sms_code"+code,5, TimeUnit.MINUTES);
        HashMap<String, String> map = new HashMap<>();
        map.put("code",code+"");
        map.put("phone",phone);
        rabbitTemplate.convertAndSend("sms",map);
    }
    public void regist(User user,String code){
        //从redis服务器中取得验证码
       String codestr=(String)redisTemplate.boundValueOps("sms_code_phone"+user.getMobile()).get();
       if(StringUtils.isEmpty(codestr)){
           //验证码为空
           throw new RuntimeException("验证码为空，请重新获取");
       }else if(!codestr.equals("sms_code"+code)){
           throw new RuntimeException("验证码输入有误，请重新获取");
       }else{
           //验证码对的 进行注册
           user.setId(idWorker.nextId()+"");
           user.setLastdate(new Date());
           user.setOnline(0L);
           user.setRegdate(new Date());
           user.setUpdatedate(new Date());
           user.setFanscount(0);
           user.setFollowcount(0);
           userDao.insert(user);

       }
    }
}
